<template>
  <div v-if="isShow" :id="echartId"  shallowRef="Echarts" style="overflow: hidden;min-height: 120px"></div>
  <el-scrollbar v-else><el-empty description="暂无数据" :image-size="100"/></el-scrollbar>
</template>
<script>
import { defineComponent, toRefs, reactive, onMounted,ref,watch,onUnmounted,onActivated } from 'vue'
import * as echarts from 'echarts'
import { toThousands } from '@/utils/number-util'

export default defineComponent({
  name: 'BarMultipleEchart',
  props: {
    echartData: Object,
    echartId:String
  },
  setup(props) {
    let isShow = ref(true)
    let seriesData = ref([])
    const state = reactive({
      option: {}
    })
    const renderEchartBar = () => {
      state.option = {
        tooltip: {
          trigger: 'axis',
          confine: true,
          padding:10,
          extraCssText: "width:120px;white-space:pre",
          formatter: (params) => {
            let templete = ''
            templete = params[0].name  + '\n'
            let unit = props.echartData.yData[0].unit
            for (let i = 0 ; i<params.length; i++) {
              let item= params[i];
              let nameString = (item.seriesName+`:  `+toThousands(item.value ) + (unit?unit:''))
              templete+=nameString
              templete += (i != params.length-1)?`\n`:''
            }
            return templete
          },
        },
        color: ['#C09F88','#FF690A'],
        grid: {
          //以div为中心 向右缩进30%
          left: "2%",
          right: "0%",
          top: "18%",
          bottom: "5%",
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            // data: ['租赁', '物业', '多径'],
            data: props.echartData.xData,
            axisLine: {
              lineStyle: {
                color: '#cfd1d3', // 坐标刻度线
                width:'0.5'
              },
            },
            axisLabel:{
              // show:true,
              interval: 0,  // 强制让所有的字段展示
              rotate: props.echartData.xData.length > 4 ?30:0,   // 将字段旋转30度
              textStyle:{
                color:'#333333', // 标签文字
                fontSize: 10
              }
            },
            axisTick: {		//Y轴刻度线
              show:false,
              alignWithLabel: true,
            }
          },
        ],
        series: seriesData.value,
        yAxis:  {
          type: 'value',
          splitNumber:3,
          axisLabel:{
            show:false,
            // inside:true,        // 标签刻度朝内
            // margin:200,           // 清除默认间距
            // interval: 5000,
            // minInterval:1000,
            // maxInterval: 20000,
            // padding:[20,10,0,0], // 右边内边距10
            textStyle:{
              align:'right',   // 文字右对齐
              color:'#333333',
              fontWeight:'600'
            }
          },
          splitLine: {
            show: true,
            length: 4,
            lineStyle:{
              type:'dashed', //背景线条设置
              color:"#EAEBEB"
            }
          },
          axisLine: {
            lineStyle: {
              color: '#EAEBEB',
            },
          },
          axisTick: {		//Y轴刻度线
            show:false,
            alignWithLabel: true,
          },
        },
      }
    }
    const initeCharts = () => {
      let myChart = echarts.init(document.getElementById(props.echartId))
      // 绘制图表
      document.getElementById(props.echartId).setAttribute('_echarts_instance','')
      myChart.setOption(state.option)
      window.addEventListener("resize", () => {myChart.resize()},true)
    }
    const packageSeriesData = () => {
      seriesData.value = []
      if(props.echartData.yData && props.echartData.yData.length > 0){
        let yDatalen= props.echartData.yData.length
        props.echartData.yData.forEach(function (item,index) {
          let series = {
              name: item.name,
              data: item.data,
              type: "bar",
              barWidth: '10',
              barMaxWidth:'10',
              barMinWidth:'0',
              barGap:index ==yDatalen-1?'200%':'0', // 后面一根柱子需要设置间距
              showBackground: false,
              itemStyle: {
                normal: {
                  //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
                  barBorderRadius: [2, 2, 2, 2],
                  label: {
                    confine: true,
                    show:  true, //开启数值显示显示
                    position: 'top', //在上方显示
                    formatter:function (params){
                      if(params.value){
                        return toThousands(params.value) + (item.unit?item.unit:'')
                      } else {
                        return ""
                      }
                    },
                    textStyle: { //数值样式
                      color: '#C09F88',
                      fontSize: 10
                    }
                  }
                }
              },
              backgroundStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
              }
            }
            seriesData.value.push(series)
        })
        console.log(seriesData.value)
        renderEchartBar()

      }
    }
    onMounted(() => {
    })
    onUnmounted(() => {
      // document.getElementById(props.echartId) ?myChart.dispose():'' // （在图表容器被销毁之后，调用 echartsInstance.dispose 销毁实例）
    })
    onActivated(() => {
      let myEchart = document.getElementById(props.echartId)
      if(myEchart){
        myEchart.removeAttribute('_echarts_instance_');
        setTimeout(() => {
                initeCharts()
              }, 200)
      }
    })
    watch(
        ()=>props.echartData,
        (val,preVal)=>{
          //val为修改后的值,preVal为修改前的值
          console.log("message",val,preVal)
          if(!val.yData || val.yData.length < 1) {
            isShow.value = false
          }else {
            isShow.value = true
            packageSeriesData()
            setTimeout(() => {
              initeCharts()
            }, 600)
          }
        },
        {
          //如果加了这个参数，值为true的话，就消除了惰性，watch会在创建后立即执行一次
          //那么首次执行，val为默认值,preVal为undefined
          immediate:true,
          //这个参数代表监听对象时，可以监听深度嵌套的对象属性
          //比如message是一个对象的话，可以监听到message.a.b.c，也就是message下的所有属性
          deep:true,
        }
    )
    return {
      isShow,seriesData,...toRefs(state)
    }
  },
})
</script>

<style lang="scss" scoped>
</style>
